# -*- coding:utf-8 -*-

__author__ = 'zhaoxp'

class Resistor(object):

    def __init__(self,ohms):
        self.ohms = ohms
        self.voltage = 0
        self.current = 0


class VoltageResistor(Resistor):
    def __init__(self,ohms):
        super(VoltageResistor,self).__init__(ohms)
        self._voltage = 0

    @property
    def voltage(self):
        return self._voltage
    
    @voltage.setter
    def voltage(self,voltage):
        self._voltage = voltage
        self.current = self._voltage / self.ohms


class BoundedResistance(Resistor):
    def __init__(self,ohms):
        super(BoundedResistance,self).__init__(ohms)

    @property
    def ohms(self):
        return self._ohms
    
    @ohms.setter
    def ohms(self,ohms):
        if ohms<=0:
            raise ValueError('%f ohms must be > 0'%ohms)
        self._ohms = ohms


class FixedResistance(Resistor):

    @property
    def ohms(self):
        return self._ohms
    
    @ohms.setter
    def ohms(self,ohms):
        if hasattr(self,'_ohms'):
            raise AttributeError('Can not set attribute(ohms)')
        self._ohms = ohms


##########################################################################

class C(object):

    def __init__(self):
        self._x = None

    def getx(self):
        print('call C.getx')
        return self._x

    def setx(self,value):
        print('call C.setx')
        self._x = value

    def delx(self):
        print('call C.delx')
        del self._x

    x = property(getx,setx,delx,"I'm the 'x' property")


if __name__ == '__main__':
    print('Use plain attributes instread of get and set methods')
    v = VoltageResistor(1e3)
    print('Before: %5r amps'%v.current)
    v.voltage = 10
    print('After:  %5r amps'%v.current)
    v.voltage = 13
    print('After:  %5r amps'%v.current)
    print('-'*30)
    v2 = BoundedResistance(1e3)
    try:
        v2.ohms = 0
    except ValueError as ve:
        print('ValueError %s'%ve)
    print('-'*30)
    try:
        BoundedResistance(-4)
    except ValueError as ve:
        print('ValueError %s'%ve)        
    print('-'*30)
    v3 = FixedResistance(1e3)
    try:
        v3.ohms = 2e3
    except AttributeError as ae:
        print('AttributeError: %s'%ae)
    
    print('-'*30)
    c = C()
    print('Before: c.x = %s'%c.x)
    c.x = 10
    print('After:  c.x = %s'%c.x)